package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.CustomerReturnListGoodsDao;
import com.atguigu.jxc.dao.GoodsDao;
import com.atguigu.jxc.dao.UserDao;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.domain.SuccessCode;
import com.atguigu.jxc.entity.*;
import com.atguigu.jxc.service.CustomerReturnListGoodsService;
import com.atguigu.jxc.service.LogService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import jdk.nashorn.internal.parser.TokenType;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author :ttm
 * @description :
 */
@Service
public class CustomerReturnListGoodsServiceImpl implements CustomerReturnListGoodsService {
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CustomerReturnListGoodsDao customerReturnListGoodsDao;
    @Autowired
    private LogService logService;

    @Override
    public ServiceVO save(CustomerReturnList customerReturnList, String customerReturnListGoodsStr) {
        Gson gson = new Gson();
        List<CustomerReturnListGoods> customerReturnListList= gson.fromJson(customerReturnListGoodsStr, new TypeToken<List<CustomerReturnListGoods>>() {
        }.getType());
        User currentUser = userDao.findUserByName((String) SecurityUtils.getSubject().getPrincipal());
        customerReturnList.setUserId(currentUser.getUserId());
        customerReturnListGoodsDao.saveCustomerReturnList(customerReturnList);
        for (CustomerReturnListGoods customerReturnListGoods : customerReturnListList) {
            customerReturnListGoods.setCustomerReturnListId(customerReturnList.getCustomerReturnListId());
            customerReturnListGoodsDao.saveCustomerReturnListGoods(customerReturnListGoods.getCustomerReturnListGoodsId());
            Goods goods = goodsDao.findByGoodsId(customerReturnListGoods.getGoodsId());
            goods.setInventoryQuantity(goods.getInventoryQuantity()+customerReturnListGoods.getGoodsNum());
            goods.setState(2);
            goodsDao.updateGoods(goods);
        }
        // 保存日志
        logService.save(new Log(Log.INSERT_ACTION, "新增客户退货单："+customerReturnList.getReturnNumber()));

        return new ServiceVO<>(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS);
    }
}
